package com.zhou.push;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.net.Socket;

/**
 * Created by zhou on 2016/3/13.
 */
public class PushService extends Service {

    private Socket socket = null;
    private IMReader imReader;
    private IMWriter imWriter;
    private boolean isConnect = true;


    @Override
    public void onCreate() {
        super.onCreate();
    }

    /**
     * 连接服务器如果第一次失败可以两秒之后重新连接
     */
    private void connectServer(final ICallBack cb){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket("192.168.31.52",8888);
                    imReader = new IMReader(socket.getInputStream(),cb);
                    imWriter = new IMWriter(socket.getOutputStream());
                    imReader.start();
                    imWriter.start();
                    isConnect = true;
                } catch (IOException e) {
                    e.printStackTrace();
                    isConnect = false;
                    try {
                        Thread.sleep(2000);
                        connectServer(cb);
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }).start();

    }

    @Override
    public IBinder onBind(Intent intent) {
        return iBind;
    }

    //本地实现AIDL方法
    private final Push.Stub iBind = new Push.Stub() {
        @Override
        public boolean connect(ICallBack cb) throws RemoteException {
            connectServer(cb);
            return true;
        }

        @Override
        public boolean sendMsg(String msg) throws RemoteException {
            return imWriter.sendMsg(msg);
        }
    };
}
